<template>
  <div class="check-report">
    <div class="toolbar">
      <el-radio-group v-model="quickRange" size="small" @change="onQuickRange">
        <el-radio-button label="today">今日</el-radio-button>
        <el-radio-button label="yesterday">昨日</el-radio-button>
        <el-radio-button label="week">本周</el-radio-button>
        <el-radio-button label="lastWeek">上周</el-radio-button>
        <el-radio-button label="month">本月</el-radio-button>
        <el-radio-button label="lastMonth">上月</el-radio-button>
        <el-radio-button label="custom">自定义时间</el-radio-button>
      </el-radio-group>
      <el-date-picker
        v-model="dateRange"
        type="datetimerange"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        value-format="YYYY-MM-DD HH:mm:ss"
        :disabled="quickRange !== 'custom'"
        style="margin-left:12px;width:420px"
      />
    </div>

    <div class="filter-section">
      <el-row :gutter="12">
        <el-col :span="6">
          <el-input v-model="query.goodsOrCategory" placeholder="请输入货品名称/编号" clearable />
        </el-col>
        <el-col :span="6">
          <el-input v-model="query.transferOrderNo" placeholder="请输入调拨单号" clearable />
        </el-col>
        <el-col :span="6">
          <el-select v-model="query.transferType" placeholder="请选择调拨类型" clearable>
            <el-option label="草稿" value="Draft" />
            <el-option label="待审核" value="Pending" />
            <el-option label="已审核" value="Approved" />
            <el-option label="已完成" value="Completed" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-input v-model="query.makerName" placeholder="请输入制单人" clearable />
        </el-col>
      </el-row>
      <el-row :gutter="12" style="margin-top:12px">
        <el-col :span="6">
          <el-select v-model="query.goodsType" placeholder="请选择货品类型" clearable>
            <el-option label="电器类" value="电器类" />
            <el-option label="饮品" value="饮品" />
            <el-option label="食品" value="食品" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select v-model="query.unit" placeholder="请选择单位" clearable>
            <el-option label="个" value="个" />
            <el-option label="瓶" value="瓶" />
            <el-option label="箱" value="箱" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-input v-model="query.agentName" placeholder="请输入经办人" clearable />
        </el-col>
        <el-col :span="6">
          <el-select v-model="query.fromWarehouse" placeholder="请选择调出仓库" clearable>
            <el-option label="货品仓库一" value="货品仓库一" />
            <el-option label="货品仓库二" value="货品仓库二" />
            <el-option label="货品仓库三" value="货品仓库三" />
          </el-select>
        </el-col>
      </el-row>
      <el-row :gutter="12" style="margin-top:12px">
        <el-col :span="6">
          <el-select v-model="query.toWarehouse" placeholder="请选择调入仓库" clearable>
            <el-option label="货品仓库一" value="货品仓库一" />
            <el-option label="货品仓库二" value="货品仓库二" />
            <el-option label="货品仓库三" value="货品仓库三" />
          </el-select>
        </el-col>
        <el-col :span="18">
          <div class="status-checkboxes">
            <span>出入库状态：</span>
            <el-checkbox-group v-model="statusFilters">
              <el-checkbox label="all">全部</el-checkbox>
              <el-checkbox label="notInbound">未入库</el-checkbox>
              <el-checkbox label="inbound">已入库</el-checkbox>
              <el-checkbox label="partialInbound">部分入库</el-checkbox>
              <el-checkbox label="notOutbound">未出库</el-checkbox>
              <el-checkbox label="outbound">已出库</el-checkbox>
              <el-checkbox label="partialOutbound">部分出库</el-checkbox>
            </el-checkbox-group>
          </div>
        </el-col>
      </el-row>
      <div class="action-buttons" style="margin-top:12px">
        <el-button @click="reset">重置</el-button>
        <el-button type="primary" @click="loadData(1)">查询</el-button>
      </div>
    </div>

    <div class="cards">
      <el-card class="card" shadow="never">
        <div class="num">{{ stats.transferOrderCount }}</div>
        <div class="desc">调拨单数量</div>
      </el-card>
      <el-card class="card" shadow="never">
        <div class="num">{{ stats.transferQuantity }}</div>
        <div class="desc">调拨货品数量</div>
      </el-card>
      <el-card class="card" shadow="never">
        <div class="num green">{{ formatMoney(stats.transferAmount) }}</div>
        <div class="desc">调拨产品金额</div>
      </el-card>
    </div>

    <div class="table-actions">
      <el-button @click="onExport">导出</el-button>
      <el-button @click="loadData()">刷新</el-button>
    </div>

    <el-table :data="tableData" border style="width:100%" height="520">
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="transferOrderNo" label="调拨单号" width="140" />
      <el-table-column prop="applyDate" label="调拨申请日期" width="120">
        <template #default="{ row }">{{ formatDate(row.applyDate) }}</template>
      </el-table-column>
      <el-table-column prop="fromWarehouse" label="调出仓库" width="120" />
      <el-table-column prop="toWarehouse" label="调入仓库" width="120" />
      <el-table-column prop="goodsName" label="货品名称" min-width="160" />
      <el-table-column prop="transferQuantity" label="调拨数量" width="100" />
      <el-table-column prop="transferAmount" label="调拨金额" width="120">
        <template #default="{ row }">{{ formatMoney(row.transferAmount) }}</template>
      </el-table-column>
      <el-table-column prop="outStatus" label="出库状态" width="100">
        <template #default="{ row }">{{ getStatusText(row.outStatus) }}</template>
      </el-table-column>
      <el-table-column prop="inStatus" label="入库状态" width="100">
        <template #default="{ row }">{{ getStatusText(row.inStatus) }}</template>
      </el-table-column>
      <el-table-column prop="agentName" label="经办人" width="100" />
      <el-table-column prop="makerName" label="制单人" width="100" />
      <el-table-column prop="deptName" label="所在部门" width="120" />
      <el-table-column prop="makeTime" label="制单时间" width="160">
        <template #default="{ row }">{{ formatTime(row.makeTime) }}</template>
      </el-table-column>
    </el-table>

    <div class="pager">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-sizes="[10,20,50,100]"
        v-model:current-page="page"
        v-model:page-size="pageSize"
        @size-change="loadData(1)"
        @current-change="loadData"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import { ref, reactive, watch } from 'vue'
import { fetchTransferPage, fetchTransferStats, type GetTransferInput } from '/@/api/report/check'

const tableData = ref<any[]>([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(10)

const quickRange = ref<'today'|'yesterday'|'week'|'lastWeek'|'month'|'lastMonth'|'custom'>('month')
const dateRange = ref<[string,string]|null>(null)

const query = reactive<{ 
  goodsOrCategory?: string
  transferOrderNo?: string
  transferType?: string
  makerName?: string
  goodsType?: string
  unit?: string
  agentName?: string
  fromWarehouse?: string
  toWarehouse?: string
}>({})

const statusFilters = ref<string[]>(['all'])

function computeRange() {
  const now = dayjs()
  switch (quickRange.value) {
    case 'today': return [now.startOf('day').format('YYYY-MM-DD HH:mm:ss'), now.endOf('day').format('YYYY-MM-DD HH:mm:ss')]
    case 'yesterday': { const y = now.subtract(1,'day'); return [y.startOf('day').format('YYYY-MM-DD HH:mm:ss'), y.endOf('day').format('YYYY-MM-DD HH:mm:ss')] }
    case 'week': return [now.startOf('week').format('YYYY-MM-DD HH:mm:ss'), now.endOf('day').format('YYYY-MM-DD HH:mm:ss')]
    case 'lastWeek': { const lw = now.subtract(1,'week'); return [lw.startOf('week').format('YYYY-MM-DD HH:mm:ss'), lw.endOf('week').format('YYYY-MM-DD HH:mm:ss')] }
    case 'month': return [now.startOf('month').format('YYYY-MM-DD HH:mm:ss'), now.endOf('day').format('YYYY-MM-DD HH:mm:ss')]
    case 'lastMonth': { const lm = now.subtract(1,'month'); return [lm.startOf('month').format('YYYY-MM-DD HH:mm:ss'), lm.endOf('month').format('YYYY-MM-DD HH:mm:ss')] }
    default: return dateRange.value ?? null
  }
}

function buildPayload(p = page.value): GetTransferInput {
  const range = computeRange()
  return {
    startTime: range?.[0],
    endTime: range?.[1],
    goodsOrCategory: query.goodsOrCategory,
    transferOrderNo: query.transferOrderNo,
    transferType: query.transferType,
    makerName: query.makerName,
    agentName: query.agentName,
    fromWarehouse: query.fromWarehouse,
    toWarehouse: query.toWarehouse,
    page: p,
    pageSize: pageSize.value,
  }
}

async function loadData(p?: number) {
  if (p) page.value = p
  const payload = buildPayload()
  const [pageRes, statsRes] = await Promise.all([
    fetchTransferPage(payload),
    fetchTransferStats(payload),
  ])
  
  // 与盘点统计一致：从 data.result.result 读取
  const pageData = pageRes?.data?.result?.result
  if (pageData) {
    tableData.value = pageData.items || []
    total.value = pageData.total || 0
  } else {
    tableData.value = []
    total.value = 0
  }
  
  // 统计数据：data.result.result
  const statsData = statsRes?.data?.result?.result
  if (statsData) {
    stats.value = {
      transferOrderCount: statsData.transferOrderCount || 0,
      transferQuantity: statsData.transferQuantity || 0,
      transferAmount: statsData.transferAmount || 0,
    }
  } else {
    stats.value = {
      transferOrderCount: 0,
      transferQuantity: 0,
      transferAmount: 0,
    }
  }
}

function reset() {
  quickRange.value = 'month'
  dateRange.value = null
  Object.keys(query).forEach(k => (query as any)[k] = undefined)
  statusFilters.value = ['all']
  loadData(1)
}

function onQuickRange() {
  if (quickRange.value !== 'custom') dateRange.value = null
  loadData(1)
}

function onExport() {
  // 预留：可调用后端导出接口
}

function getStatusText(status: string) {
  const statusMap: Record<string, string> = {
    'NotOutOfWarehouse': '未出库',
    'OutOfWarehouse': '已出库',
    'PartialOutOfWarehouse': '部分出库',
    'NotInWarehouse': '未入库',
    'InWarehouse': '已入库',
    'PartialInWarehouse': '部分入库',
  }
  return statusMap[status] || status
}

const stats = ref({ transferOrderCount: 0, transferQuantity: 0, transferAmount: 0 })

function formatMoney(n: number) { return new Intl.NumberFormat('zh-CN', { style: 'currency', currency: 'CNY', maximumFractionDigits: 2 }).format(n || 0) }
function formatDate(d: string | Date) { if (!d) return ''; return dayjs(d).format('YYYY-MM-DD') }
function formatTime(t: string | Date) { if (!t) return ''; const d = typeof t === 'string' ? new Date(t) : t; return dayjs(d).format('YYYY-MM-DD HH:mm:ss') }

watch(pageSize, () => loadData(1))

loadData(1)
</script>

<style scoped>
.check-report { padding: 12px; }
.toolbar { display: flex; align-items: center; margin-bottom: 12px; }
.filter-section { background: #f5f5f5; padding: 16px; border-radius: 4px; margin-bottom: 12px; }
.status-checkboxes { display: flex; align-items: center; gap: 8px; }
.action-buttons { text-align: right; }
.cards { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; margin: 12px 0; }
.card { text-align: center; }
.num { font-size: 24px; font-weight: 700; }
.num.green { color: #18a058; }
.desc { color: #888; margin-top: 4px; font-size: 12px; }
.table-actions { margin: 12px 0; }
.pager { margin-top: 10px; display: flex; justify-content: flex-end; }
</style>
